package com.nbjtjc.safe.service.emg;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.emg.EmgDutyMapper;
import com.nbjtjc.safe.mapper.emg.EmgPlanPublicMapper;
import com.nbjtjc.safe.mapper.emg.EmgPlanPublicSummaryMapper;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.model.emg.EmgDuty;
import com.nbjtjc.safe.model.emg.EmgPlanPublic;
import com.nbjtjc.safe.model.emg.EmgPlanPublicSummary;
import com.nbjtjc.safe.model.sys.SysUser;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class EmgPlanPublicSummaryService {
    @Autowired
    private EmgPlanPublicSummaryMapper emgPlanPublicSummaryMapper;
    @Autowired
    private EmgPlanPublicMapper emgPlanPublicMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private EmgDutyMapper emgDutyMapper;
    @Transactional(rollbackFor = {Throwable.class})
    public Result delete(int emgPlanPublicSummaryId) {
        Result result = new Result();
        emgPlanPublicSummaryMapper.deleteByPrimaryKey(emgPlanPublicSummaryId);
        return result;
    }

    public Result find(EmgPlanPublicSummary emgPlanPublicSummary, Page page) {
        Result result = new Result();
        PageHelper.startPage(page.getPageCurrent(), page.getPageSize());
        List<EmgPlanPublicSummary> emgPlanPublicSummaries = emgPlanPublicSummaryMapper
                .search(emgPlanPublicSummary, page);
        result.setData(new PageInfo<>(emgPlanPublicSummaries));
        return result;
    }

    public Result findLowerDeptSummary(EmgPlanPublicSummary emgPlanPublicSummary) {
        Result result = new Result();
        if(!isEmgPlanPublicCreateByMyCompany(emgPlanPublicSummary)){
            String pathId=emgPlanPublicMapper.getPathId(emgPlanPublicSummary.getPlanPublicId());
            EmgPlanPublic emgPlanPublic=emgPlanPublicMapper.getPlanPublicByPathId(pathId
                    ,false,MyShiroUtils.getCompanyId());
            if(ObjectUtil.isNotNull(emgPlanPublic)){
                emgPlanPublicSummary.setPlanPublicId(emgPlanPublic.getStartPlanId());
            }
        }
        List<Integer> subCompanyIds = sysDeptMapper.getSubCompanyId(MyShiroUtils.getCompanyId()
                , Constant.SysDeptType.COMPANY.getValue());
        if (CollectionUtil.isEmpty(subCompanyIds)) {
            result.setFalse("没有子公司");
            return result;
        }
        emgPlanPublicSummary.setCompanyIds(subCompanyIds);
        List<EmgPlanPublicSummary> summaries = emgPlanPublicSummaryMapper
                .search(emgPlanPublicSummary, new Page());
        if (CollectionUtil.isEmpty(summaries)) {
            result.setMessage("暂时没有上报数据");
            return result;
        }
        EmgPlanPublic emgPlanPublic = emgPlanPublicMapper.selectByPrimaryKey
                (summaries.get(0).getPlanPublicId());
        Map<Integer, EmgPlanPublicSummary> summaryMap = new HashMap<>();
        summaries.forEach(summary -> {
            //判断去除发布部门自己的总结，只显示其他部门对该响应的总结
            if (summaryMap.containsKey(summary.getDeptId())) {
                if (summaryMap.get(summary.getDeptId()).getCreateTime()
                        .compareTo(summary.getCreateTime()) < 0) {
                    summaryMap.put(summary.getDeptId(), summary);
                }
            } else {
                summaryMap.put(summary.getDeptId(), summary);
            }
        });
        HashMap<String, List<Map<String, String>>> summaryInfoMap = new HashMap<>();
        initSummaryInfoMap(summaryInfoMap);
        summaryMap.entrySet().forEach(entry -> {
            EmgPlanPublicSummary summary = entry.getValue();
            Map<String, String> responseSituationMap = new HashMap<>();
            responseSituationMap.put("content", summary.getResponseSituation());
            responseSituationMap.put("companyName", summary.getCompanyName());
            responseSituationMap.put("date", DateUtil.format(summary.getCreateTime(), "yyyy-MM-dd hh:mm:ss"));
            summaryInfoMap.get("responseSituation").add(responseSituationMap);

            Map<String, String> effectEvaluationMap = new HashMap<>();
            effectEvaluationMap.put("content", summary.getEffectEvaluation());
            effectEvaluationMap.put("companyName", summary.getCompanyName());
            effectEvaluationMap.put("date", DateUtil.format(summary.getCreateTime(), "yyyy-MM-dd hh:mm:ss"));
            summaryInfoMap.get("effectEvaluation").add(effectEvaluationMap);

            Map<String, String> damagedUnitMap = new HashMap<>();
            damagedUnitMap.put("content", summary.getDamagedUnit());
            damagedUnitMap.put("companyName", summary.getCompanyName());
            damagedUnitMap.put("date", DateUtil.format(summary.getCreateTime(), "yyyy-MM-dd hh:mm:ss"));
            summaryInfoMap.get("damagedUnit").add(damagedUnitMap);

            Map<String, String> deathSituationMap = new HashMap<>();
            deathSituationMap.put("content", summary.getDeathSituation());
            deathSituationMap.put("companyName", summary.getCompanyName());
            deathSituationMap.put("date", DateUtil.format(summary.getCreateTime(), "yyyy-MM-dd hh:mm:ss"));
            summaryInfoMap.get("deathSituation").add(deathSituationMap);

            Map<String, String> econLossSituationMap = new HashMap<>();
            econLossSituationMap.put("content", summary.getEconLossSituation());
            econLossSituationMap.put("companyName", summary.getCompanyName());
            econLossSituationMap.put("date", DateUtil.format(summary.getCreateTime(), "yyyy-MM-dd hh:mm:ss"));
            summaryInfoMap.get("econLossSituation").add(econLossSituationMap);

            Map<String, String> econLossEstimateMap = new HashMap<>();
            econLossEstimateMap.put("content", summary.getEconLossEstimate());
            econLossEstimateMap.put("companyName", summary.getCompanyName());
            econLossEstimateMap.put("date", DateUtil.format(summary.getCreateTime(), "yyyy-MM-dd hh:mm:ss"));
            summaryInfoMap.get("econLossEstimate").add(econLossEstimateMap);
        });
        result.setData(summaryInfoMap);
        return result;
    }

    @Transactional(rollbackFor = {Throwable.class})
    public Result add(EmgPlanPublicSummary summary) {
        Result result = new Result();
        int res = 0;
        if (ObjectUtil.isNull(summary) || ObjectUtil.isNull(summary.getPlanPublicId())) {
            result.setFalse("不能为空，预案模板的id");
            return result;
        }
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("user");
        summary.setCompanyId(sysUser.getCompanyId());
        summary.setDeptId(sysUser.getDeptId().intValue());
        summary.setWriteUserId(sysUser.getUserId());
        summary.setCreateTime(new Date());
        res = emgPlanPublicSummaryMapper.insertSelective(summary);
        if (res == 0) {
            result.setFalse("插入失败");
            return result;
        }
        result.setData(summary);
        return result;
    }

    @Transactional(rollbackFor = {Throwable.class})
    public Result update(EmgPlanPublicSummary summary) throws Exception {
        Result result = new Result();
        int res = 0;
        if (ObjectUtil.isNull(summary) || ObjectUtil.isNull(summary.getId())) {
            result.setFalse("不能为空 ");
            return result;
        }

        res = emgPlanPublicSummaryMapper.updateByPrimaryKeySelective(summary);
        if (res == 0) {
            throw new Exception("更新发布计划失败");
        }
        result.setData(summary);
        return result;
    }
    public Map<String,Object> writeable(int planPublicId){
        Map<String, Object> datas = new HashMap<>();
        EmgDuty emgDuty=new EmgDuty();
        emgDuty.setUserId(MyShiroUtils.getSessionUserId());
        emgDuty.setPlanPublicId(planPublicId);
        List<EmgDuty> emgDuties=emgDutyMapper.select(emgDuty);
        if(CollectionUtil.isEmpty(emgDuties)){
            datas.put("write",false);
            return datas;
        }
        String dateStr=DateUtil.format(new Date(),"yyyy-MM-dd");
        emgDuties.forEach(duty->{
            String dutyStr=DateUtil.format(duty.getDutyDate(),"yyyy-MM-dd");
            if(datas.containsKey("write")){
                if(!(Boolean) datas.get("write")){
                    if(dutyStr.equals(dateStr)){
                        datas.put("write",true);
                    }
                }
            }else{
                if(dutyStr.equals(dateStr)){
                    datas.put("write",true);
                }else{
                    datas.put("write",false);
                }
            }
        });
        return datas;
    }

    private void initSummaryInfoMap(HashMap<String, List<Map<String, String>>> summaryInfoMap) {
        summaryInfoMap.put("responseSituation", new ArrayList<>());
        summaryInfoMap.put("effectEvaluation", new ArrayList<>());
        summaryInfoMap.put("damagedUnit", new ArrayList<>());
        summaryInfoMap.put("deathSituation", new ArrayList<>());
        summaryInfoMap.put("econLossSituation", new ArrayList<>());
        summaryInfoMap.put("econLossEstimate", new ArrayList<>());
    }

    /**
     * 判断当前需要获取下级工作简报的是不是自己公司发布的应急预案
     */
    private boolean isEmgPlanPublicCreateByMyCompany(EmgPlanPublicSummary emgPlanPublicSummary){
        int planPublicCompanyId=emgPlanPublicMapper.getCompanyId(emgPlanPublicSummary.getPlanPublicId());
        if(MyShiroUtils.getCompanyId().equals(planPublicCompanyId)){
            return true;
        }else{
            return false;
        }

    }
}
